//
//  NetworkHelper.m
//  YAMainProject
//
//  Created by 郑逸凯 on 2018/11/2.
//  Copyright © 2018年 郑逸凯. All rights reserved.
//

#import "NetworkHelper.h"
#import <AFNetworking/AFNetworking.h>

@interface NetworkHelper ()

@property (nonatomic,strong)AFNetworkReachabilityManager *networkReachabilityManager;

@end

@implementation NetworkHelper

+ (instancetype)sharedInstance {
    static NetworkHelper *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 要使用self来调用
        _sharedInstance = [[self alloc] init];
        _sharedInstance.networkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    });
    return _sharedInstance;
}

- (void)hasNetwork:(void(^)(bool has))hasNet{
    //创建网络监听对象
    AFNetworkReachabilityManager *manager = self.networkReachabilityManager;
    //开始监听
    [manager startMonitoring];
    //监听改变
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
            case AFNetworkReachabilityStatusNotReachable:
                hasNet(NO);
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                hasNet(YES);
                break;
        }
    }];
}


+ (NSError *)woResponseSuccess:(id)responseObject {
    if ([responseObject isKindOfClass:NSDictionary.class] && (responseObject[@"code"] != nil)) {
        NSInteger code = [responseObject[@"code"] integerValue];
        if ( code == 200) {
            return nil;
        }else {
            return [NetworkHelper errorWithCode:code];
        }
    }
    return [NSError errorWithDomain:@"服务器异常,请稍后再试" code:-1 userInfo:nil];
}


+ (NSError *)errorWithCode:(NSInteger)code {
    NSString *errorString = @"服务器异常,请稍后再试";
    
    switch (code) {
        case 20509:
            errorString = @"登录失效";
            break;
        case 20228:
            errorString = @"用户名不存在";
            break;
        case 20227:
            errorString = @"用户名不能为空";
            break;
        case 20326:
            errorString = @"密码错误";
            break;
        case 20707:
            errorString = @"请求不支持该方法";
            break;
        case 21022:
            errorString = @"内容超过限制大小（数量过多）";
            break;
        case 20705:
            errorString = @"请求没有权限";
            break;
        case 21012:
            errorString = @"内容格式错误";
            break;
        case 20825:
            errorString = @"文件为空";
            break;
        case 21010:
            errorString = @"数据已存在";
            break;
        default:
            break;
    }
    return [NSError errorWithDomain:errorString code:code userInfo:nil];
}



@end
